"""HIS 药品字典路由

包含药品字典相关的 API 接口。
使用 FastAPI-Pagination 库实现现代化分页功能。
"""

from fastapi import APIRouter, Depends
from fastapi.responses import ORJSONResponse
import logging
from model.his.yp1 import Yp1
from core.db_manager import get_db_session
from sqlmodel import select, func
from util.saas_util import SaasException
from fastapi_pagination import Page, Params
from fastapi_pagination.ext.sqlmodel import paginate
from service.upload_drug_info_service import drug_upload_service

# 日志
logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter(prefix="/api/his", tags=["HIS 药品字典"])

@router.get("/drug-dict/count")
async def get_drug_dict_count_api():
    """获取药品字典总记录数"""
    try:
        logger.info(f"开始统计药品字典总记录数")
        # 直接操作数据库获取记录数
        with get_db_session() as session:
            statement = select(func.count(Yp1.idm))
            count = session.execute(statement).scalar()
        return ORJSONResponse(
            {
            "returnCode": 0,
            "returnMsg": "获取药品字典总记录数成功",
            "count": count
            }
        )
    except Exception as e:
        logger.error(f"统计药品字典总记录数失败: {str(e)}")
        return ORJSONResponse(
            {
                "returnCode": -1,
                "returnMsg": "获取药品字典总记录数失败"+ str(e)
            }
        )

@router.get("/drug-dict/page")
async def get_drug_dict_page_api(params: Params = Depends()):
    """获取药品字典分页数据"""
    try:
        logger.info(f"开始获取药品字典分页数据，页码: {params.page}, 每页大小: {params.size}")
        
        with get_db_session() as session:
            statement = select(Yp1).order_by(Yp1.ypmc)
            paginated_result = paginate(session, statement, params)
            # 将模型对象转换为字典格式，处理Decimal类型
            items_dict = []
            for item in paginated_result.items:
                item_dict = item.model_dump(mode='json')  # 使用json模式自动处理Decimal
                items_dict.append(item_dict)
            
            # 构建统一的返回格式
            return ORJSONResponse({
                "returnCode": 0,
                "returnMsg": "获取药品字典分页数据成功",
                "resultList": items_dict,  # 转换为字典格式的数据列表
                "currentPage": paginated_result.page,
                "pageSize": paginated_result.size,
                "totalCount": paginated_result.total,
                "totalPages": paginated_result.pages,
            })
            
    except Exception as e:
        logger.error(f"获取药品字典分页数据失败: {str(e)}")
        return ORJSONResponse({
            "returnCode": -1,
            "returnMsg": "获取药品字典分页数据失败"+ str(e),
            "resultList": None,

        })

@router.post("/drug-dict/upload")
async def upload_drug_dict_api():
    """上传医院药品字典到 SaaS 平台 - 使用分批处理机制"""
    hospital_name = drug_upload_service.hospital_name
    
    try:
        logger.info(f"开始上传{hospital_name}药品字典到 SaaS 平台")
        
        # 使用药品上传服务进行分批上传
        upload_result = drug_upload_service.upload_drugs_in_batches()
        
        # 处理上传结果
        if upload_result["total_uploaded"] > 0:
            success_batches = upload_result["success_batches"]
            total_batches = upload_result["total_batches"]
            
            logger.info(f"分批上传完成，总共处理 {total_batches} 批，成功 {success_batches} 批，累计上传 {upload_result['total_uploaded']} 条数据")
            return {
                "success": True,
                "message": f"分批上传完成，成功 {success_batches}/{total_batches} 批",
                "data": {
                    "total_uploaded": upload_result["total_uploaded"],
                    "total_failed": upload_result["total_failed"],
                    "total_batches": total_batches,
                    "success_batches": success_batches,
                    "failed_batches": upload_result["failed_batches"],
                    "upload_results": upload_result["upload_results"]
                },
                "count": upload_result["total_uploaded"],
                "hospital": hospital_name
            }
        else:
            logger.warning("没有数据需要上传或上传失败")
            return {
                "success": False,
                "message": "没有数据需要上传或上传失败",
                "data": {
                    "total_uploaded": 0,
                    "total_failed": upload_result.get("total_failed", 0),
                    "total_batches": upload_result.get("total_batches", 0),
                    "success_batches": 0,
                    "failed_batches": upload_result.get("failed_batches", 0),
                    "upload_results": upload_result.get("upload_results", [])
                },
                "count": 0,
                "hospital": hospital_name
            }

    except SaasException as e:
        logger.error(f"上传{hospital_name}药品字典时发生SaaS HTTP异常: {e}")
        return ORJSONResponse(
            {
                "success": False,
                "error": str(e),
                "hospital": hospital_name
            }
        )
    except Exception as e:
        logger.error(f"上传{hospital_name}药品字典失败: {e}", exc_info=True)
        return ORJSONResponse(
            {
                "success": False,
                "error": str(e),
                "hospital": hospital_name
            }
        )




__all__ = ["router"]